// ==================== Cookie 操作工具 ====================
const CookieManager = {
    // 设置 Cookie
    set(name, value, days = 7) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = name + "=" + JSON.stringify(value) + ";" + expires + ";path=/";
    },

    // 获取 Cookie
    get(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) {
                try {
                    return JSON.parse(c.substring(nameEQ.length, c.length));
                } catch(e) {
                    return null;
                }
            }
        }
        return null;
    }
};

// ==================== URL 参数处理 ====================
function getUrlParameter(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// ==================== 登录表单处理 ====================
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');

    // 获取跳转前的页面地址
    const redirectUrl = getUrlParameter('redirect') || 'index.html';

    // 检查是否已经登录
    const userInfo = CookieManager.get('userInfo');
    if (userInfo && userInfo.userId) {
        // 已登录，直接跳转
        console.log('用户已登录，跳转到:', redirectUrl);
        window.location.href = redirectUrl;
        return;
    }

    // 处理表单提交
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();

        // 验证输入
        if (!username) {
            alert('请输入用户名');
            usernameInput.focus();
            return;
        }

        if (!password) {
            alert('请输入密码');
            passwordInput.focus();
            return;
        }

        // 使用用户名作为 userId（保持简单）
        const userId = username;

        // 保存登录信息到 Cookie
        const userInfo = {
            userId: userId,
            username: username,
            password: password,
            loginTime: new Date().toISOString()
        };

        CookieManager.set('userInfo', userInfo, 7); // 保存7天

        // 显示登录成功提示
        alert(`登录成功！欢迎 ${username}`);

        // 跳转回原页面
        console.log('登录成功，跳转到:', redirectUrl);
        window.location.href = redirectUrl;
    });

    // 自动聚焦到用户名输入框
    usernameInput.focus();
});